<?php
namespace app\home\controller;

use app\home\common\Common;
use app\home\common\Page;
use app\home\common\Pagetwo;
use app\infrastructure\uri\Request;
use app\infrastructure\uri\Uri;

/**
 * Created by PhpStorm.
 * User: YD
 * Date: 2017/4/26
 * Time: 16:52
 */
class Sms extends Common
{
    private $client;
    public  function  __construct(){
        parent::__construct();
        $this->client=new Request();
    }
    public function smsList()
    {
//         $data=require("./smsTmp.php");
//        return;
//        dd($data);
        $url=Uri::HOST.Uri::SELECTSMSTMP;
        $data=$this->client->getArrayData($url);
        if($data['code'] != 0){
            $data=[];
        }else{
           $data=$data['data'];
        }
//        dd($data);
        $this->assign('data',$data);
        return view();
    }
    /**
     * 模板添加
     */
    public function smsAdd(){
         if(\think\Request::instance()->isAjax()){
            $name=$_POST['name'];
            $comment=$_POST['comment'];
            $num=$_POST['num'];
            $is_valid=$_POST['is_valid'];
            $plantForm=$_POST['plantForm'];
             if(empty($name)){
                 return['code'=>2,'msg'=>'0x400','data'=>'please enter name'];
             }
             if(empty($comment)){
                 return['code'=>2,'msg'=>'0x400','data'=>'please enter comment'];
             }
             if(empty($num)){
                 return['code'=>2,'msg'=>'0x400','data'=>'please enter num'];
             }
             if(empty($is_valid)){
                 $is_valid=0;
             }
             if(empty($plantForm)){
                 $plantForm=1;
             }
             $url=Uri::HOST.Uri::SMSTMPADD;
             $data=[
                 'name'=>$name,
                 'tmp_num'=>$num,
                 'content'=>$comment,
                 'is_valid'=>$is_valid,
                 'plantForm'=>$plantForm,
                 'operator_name'=>session('username'),
                 'operator_id'=>session('userid')
             ];
             $addRes=$this->client->getArrayData($url,$data,3);
             return $addRes;
//             if(!file_exists('./smsTmp.php')){
//                 touch('./smsTmp.php');
//             }
//             $oldData=require('./smsTmp.php');
//             $oldData[]=[
//                 "name"=>$name,
//                 "comment"=>$comment,
//                 "num"=>$num,
//                 "create_time"=>time()
//             ];
//             $newData=var_export($oldData,true);
//              $str=<<<EOF
//       <?php return
//       {$newData} ;
//EOF;
//            $res= file_put_contents('./smsTmp.php',$str);
//             if($res){
//                 return['code'=>0,'msg'=>'0x200','data'=>'success'];
//             }
         }
        return view();
    }
    /**
     * 更改模板状态
     */
    public function updateSms(){
        if(\think\Request::instance()->isAjax()){
            $type=$_POST['type'];
            $id=$_POST['uid'];
            $url=Uri::HOST.Uri::UPDATESMSTMP.$id;
            $data=[
                'is_valid'=>$type
            ];
            $updateRes=$this->client->getArrayData($url,$data,4);
            return $updateRes;
        }
    }
    /**
     * 修改模板
     */
    public function editSms(){
        if(\think\Request::instance()->isAjax()){
            $id=$_POST['id'];
            $data=[
                "name"=>$_POST['name'],
                "tmp_num"=>$_POST['num'],
                "content"=>$_POST['comment']
            ];
            $url=Uri::HOST.Uri::UPDATESMSTMP.$id;
           return $updateRes=$this->client->getArrayData($url,$data,4);
        }
        $id=$_GET['uid'];
       $url=Uri::HOST.Uri::UPDATESMSTMP.$id;
        $oldData=$this->client->getArrayData($url);
       $this->assign('data',$oldData['data']);
        return view();
    }
    /**
     * 给用户发送短信，逾期列表短信
     */
    public function sendSms(){
        $smsTmp=$_POST['smstmp'];
        $smsNum=$_POST['tmp_num'];
        if(empty($smsTmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp!'
            ];
            return json_encode($res);
        }
        if(!isset($_POST['phone'])){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'the select phone is empty!'
            ];
            return json_encode($res);
        }
        $phoneNum=$_POST['phone'];
        $url=Uri::HOST.Uri::SENDSMS;
        foreach($phoneNum as $k=>$v){
            $repayTime=$v['repayTime'];
            $loanRepayPeriod=$v['loanRepayPeriod']-1;
            $repayTime=floor($repayTime/1000);
            $repayTime=date('Y-m-d',$repayTime);
            $repayTime=strtotime($repayTime);
            $repayTime=$repayTime+$loanRepayPeriod*24*3600;

            $month=date('m',$repayTime);
            if($month == 1){
                $month="January";
            }
            else if($month == 2){
                $month="February";
            }else if($month == 3){
                $month="March";
            }else if($month == 4){
                $month="April";
            }else if($month == 5){
                $month="May";
            }else if($month == 6){
                $month="June";
            }else if($month == 7){
                $month="July";
            }else if($month == 8){
                $month="August";
            }else if($month == 9){
                $month="September";
            }else if($month == 10){
                $month="October";
            }else if($month == 11){
                $month="November";
            }else if($month == 12){
                $month="December";
            }
            $day=date('d',$repayTime);
            $day=$day.'th';
            $repayDay=$month." ".$day;
//            dd($v['totalRepay']);
            $totalMoney=number_format($v['totalRepay'],2);
//            dd($totalMoney);
            //前两天的逾期短信
            if($smsNum == '0010'){
                $newSmsTmp=str_replace('[var]',$totalMoney,$smsTmp);
                $newSmsTmp=str_replace('[second]',$repayDay,$newSmsTmp);
            }
            //还款当天短信
            else if($smsNum == '0005'){
                $newSmsTmp=str_replace('[var]',$totalMoney,$smsTmp);
            }
            //逾期推送
            else if($smsNum == '0006'){
                $newSmsTmp=str_replace('[var]',$totalMoney,$smsTmp);
            }else{
                $newSmsTmp=$smsTmp;
            }
             $data=[
                 'phone_num'=>$v['phone'],
                 'message'=>$newSmsTmp
             ];
           $res=$this->client->getArrayData($url,$data,3);
        }
        $pushLog=[
            'smsTmp'=>$smsTmp,
            'reciver'=>json_encode($phoneNum),
            'type'=>1
        ];
        if($res['code'] != 0){
            //推送不成功
            $pushLog['status']=1;
        }else{
            //退送成功
            $pushLog['status']=3;
        }
        $pushUrl=Uri::HOST.Uri::ADDPUSHLOG;
        $this->client->getArrayData($pushUrl,$pushLog,3);
       return json_encode($res);
    }

    /**
     * 给用户发送推送
     */
    public function sendAppSms(){
        $tmp=$_POST['smstmp'];
        if(empty($tmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp'
            ];
            return $res;
        }
        $user=$_POST['phone'];
        $newUser=[];
         foreach($user as $k=>$v){
          $newUser[]=$v['userID'];
        }
        //查询要推送的用户
        $userUrl=Uri::HOST.Uri::POSTUSERLIST;
        $query=[];
        $query['id']=[
          '$in'=>$newUser
        ];
        $user=$this->client->getArrayData($userUrl,$query,3);
        $userDevice=[];
        foreach($user['data'] as $k=>$v){
            if(!empty($v['deviceId'])){
                $userDevice[]=$v['deviceId'];
            }
        }
        if(!empty($userDevice)){
           //发送推送
            $pushUrl=Uri::HOST.Uri::SENDAPPSMS;
            $data=[
                'msg'=>$tmp,
                'reciver'=>$userDevice
            ];
            $res=$this->client->getArrayData($pushUrl,$data,3);
            //记录推送历史
            $pushLog=[
                'smsTmp'=>$tmp,
                'reciver'=>json_encode($user['data']),
                'type'=>1,
            ];
            if($res['code'] != 0){
                //推送不成功
                $pushLog['status']=1;
            }else{
                //退送成功
                $pushLog['status']=3;
            }
            $pushUrl=Uri::HOST.Uri::ADDPUSHLOG;
            $this->client->getArrayData($pushUrl,$pushLog,3);
            return $res;
        }else{
            //所选用户没有deviceId
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'the select user do not have deviceId'
            ];
          return $res;
        }
    }
    /**
     * 获取app推送模板
     */
    public function getAppTmp(){
        $url=Uri::HOST.Uri::SELECTSMSTMP."?plantForm=2";
        $smsAppTmp=$this->client->getArrayData($url);
        if($smsAppTmp['code'] != 0){
            $smsAppTmp=[];
        }else{
            $smsAppTmp=$smsAppTmp['data'];
        }
        return $smsAppTmp;
    }

    /**
     * 语音催收
     */
    public function sendVoice(){
        $smsTmp=$_POST['smstmp'];
        if(empty($smsTmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp!'
            ];
            return json_encode($res);
        }
        if(empty($_POST['phone'])){
            return ["code"=>1,'msg'=>"not any data!","data"=>"not any data!"];
        }
        $phoneNum=$_POST['phone'];
        foreach($phoneNum as $k=>$v){
            $url=Uri::HOST.Uri::SENDVOICE.$v['phone'].'/'.$smsTmp;
            $res=$this->client->getArrayData($url);
        }
        return $res;
    }
    /**
     * 推送历史列表
     */
    public function pushLogList(){
        $pushLogUrl=Uri::HOST.Uri::SELECTPUSHLOG;
        $pushLogData=$this->client->getArrayData($pushLogUrl);
        if($pushLogData['code'] != 0){
          $pushLogData=[];
        }else{
            $pushLogData=$pushLogData['data'];
        }
        $this->assign('data',$pushLogData);
        return view();
    }

    /**
     * 推送详情
     */
    public function pushInfo(){
        $id=$_GET['uid'];
        $pushInfioUrl=Uri::HOST.Uri::SELECTPUSHLOG."?id=".$id;
        $pushInfoData=$this->client->getArrayData($pushInfioUrl);
         $content=$pushInfoData['data'][0];
        $reciver=json_decode($content['reciver']);
        $this->assign('reciver',$reciver);
        $this->assign('content',$content);
        return view();
    }

    /**
     *直接发短信
     */
    public function activeSendSms(){
        $smsTmp=$_POST['smstmp'];
        if(empty($smsTmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp'
            ];
            return $res;
        }
        $phone_num=$_POST['phone'];
        $smsTmp=$_POST['smstmp'];
        $url=Uri::HOST.Uri::SENDSMS;
        $data=[
            'phone_num'=>$phone_num,
            'message'=>$smsTmp
        ];
        if(isset($_POST['transactionId'])){
            $transactionUrl=Uri::HOST.Uri::UPDATELOANTRANSACTION.$_POST['transactionId'];
            $queryData=[
                'payed_user_info'=>9
            ];
            $this->client->getArrayData($transactionUrl,$queryData,4);
        }


        $res=$this->client->getArrayData($url,$data,3);
        return $res;
    }

    /**
     * 银行卡无效导致打款失败，发送短信
     */
    public function transactionFailed($phone_num,$sms){
        $url=Uri::HOST.Uri::SENDSMS;
        $data=[
            'phone_num'=>$phone_num,
            'message'=>$sms
        ];
        return $this->client->getArrayData($url,$data,3);
    }


    /**
     * 仅仅发送短信
     */
    public function onlySendSms(){
        $smsTmp=$_POST['smstmp'];
        if(empty($smsTmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp'
            ];
            return $res;
        }
        $phone_num=$_POST['phone'];
        $smsTmp=$_POST['smstmp'];
        $url=Uri::HOST.Uri::SENDSMS;
        foreach($phone_num as $k=>$v) {
            $data=[
                'phone_num'=>$v['userPhone'],
                'message'=>$smsTmp
            ];
          $res=$this->client->getArrayData($url,$data,3);
        }
        return  $res;
    }
    /**
     * 仅仅发送APP推送
     */
    public function onlySendPush(){
        $tmp=$_POST['smstmp'];
        if(empty($tmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp'
            ];
            return $res;
        }
        $user=$_POST['phone'];
        $newUser=[];
        foreach($user as $k=>$v){
            $newUser[]=$v['userID'];
        }
        //查询要推送的用户
        $userUrl=Uri::HOST.Uri::POSTUSERLIST;
        $query=[];
        $query['id']=[
            '$in'=>$newUser
        ];
        $user=$this->client->getArrayData($userUrl,$query,3);
        $userDevice=[];
        foreach($user['data'] as $k=>$v){
            if(!empty($v['deviceId'])){
                $userDevice[]=$v['deviceId'];
            }
        }
        if(!empty($userDevice)) {
            //发送推送
            $pushUrl = Uri::HOST . Uri::SENDAPPSMS;
            $data = [
                'msg' => $tmp,
                'reciver' => $userDevice
            ];
            $res= $this->client->getArrayData($pushUrl, $data, 3);
        }else{
            $res=[
                "code"=>3,
                "msg"=>"no deviceId!",
                "data"=>"no deviceId"
            ];
        }
        return $res;
    }
    /**
     * 仅仅发送语音提醒
     */
    public function onlySendVoice(){
        $smsTmp=$_POST['smstmp'];
        if(empty($smsTmp)){
            $res=[
                'code'=>2,
                'msg'=>'0x400',
                'data'=>'please select a smstmp!'
            ];
            return json_encode($res);
        }
        if(empty($_POST['phone'])){
            return ["code"=>1,'msg'=>"not any data!","data"=>"not any data!"];
        }
        $phoneNum=$_POST['phone'];
        foreach($phoneNum as $k=>$v){
            $url=Uri::HOST.Uri::SENDVOICE.$v['userPhone'].'/'.$smsTmp;
            $res=$this->client->getArrayData($url);
        }
        return $res;
    }
}